package cn.tydy.controller;

import cn.tydy.dao.Dto.Dto;
import cn.tydy.exception.LoginException;
import cn.tydy.pojo.User;
import cn.tydy.service.user.UserService;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping(value = "/sys/user")
public class UserController{
@Resource(name = "userService")
private UserService userService;

    /**
     * 登录功能
     * @param request
     * @param userCode
     * @param userPassword
     * @return
     */
    @RequestMapping("/login.do")
    public String Login(HttpServletRequest request,String userCode,String userPassword){
        User user=userService.login(userCode,userPassword);
        if(user==null){
            throw new LoginException("用户名或密码不匹配");
           /* //跳转到登录页面
            request.setAttribute("msg","用户名或密码错误");
            return "Login";*/
        }else{
            //将信息保存到session，跳转到订单列表页
            HttpSession session=request.getSession();
            session.setAttribute("user",user);
            return "redirect:/sys/bill/billList.html";
        }
    }
    /**
     * 进入添加用户页面
     */
    @RequestMapping(value = "/userList.html")
//查询所有用户 ，返回到页面 1.返回ModelAndview 2.map/model 3.servlet API
    public String toUserList(Model model){
        List<User> users=userService.listUserAll();
        model.addAttribute("users",users);
        return "userList";
    }
    /**
     * 实现用户添加功能
     */
    @RequestMapping(value = "/useradd.do",method = RequestMethod.POST)
    public String userAdd(User user, MultipartFile photo, HttpServletRequest request){
      /*  List<String> extNames=new ArrayList<String>();
        extNames.add(".png");
        extNames.add(".jpg");
        extNames.add(".gif");
        if (photo!=null){
            //获取文件名
            String oldFileName=photo.getOriginalFilename();
            //获取文件后缀名
            String hz=oldFileName.substring(oldFileName.lastIndexOf("."));
            System.out.print(hz);
            //验证是否是指定的图片格式
            if (extNames.contains(hz)){
                //验证文件大小
                if (photo.getSize()<=5000000){
                    //获取文件需要存在服务器的地址
                    String newFilePath=request.getServletContext().getInitParameter("imagepath");
                    //设置新文件名
                    String newFileName= UUID.randomUUID().toString()+hz;
                    //根据地址和名称创建文件对象File
                    File file=new File(newFilePath+newFileName);
                    //判断对象名是否存在，如果不存在创建（制作路径）
                    if (!file.exists()){
                        file.mkdirs();
                    }
                    //将传入文件内容复制到新文件中
                    try {
                        photo.transferTo(file);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //配置图片的虚拟路径，保存到user对象，传入service，进行保存
                    String relationPath="/images/"+newFileName;

                }else {
                    System.out.print("文件太大了");
                }

            }else {
                System.out.print("文件格式不对");
            }
        }*/
        //调用service实现添加
        if (userService.add(user)<0){
            //跳转到列表页
            return "redirect:/sys/user/userList.html";
        }else{
            //返回添加页面
            request.setAttribute("user",user);
            return "forward:/sys/user/addUser.html";
        }
    }
    /**
     * 进入添加用户列表页
     */
    @RequestMapping(value = "/addUser.html")
    public String toUserAdd(){
        return "useradd";
    }
    @ExceptionHandler(value = RuntimeException.class)
    public  String handlerException(RuntimeException e,HttpServletRequest request){
        request.setAttribute("e",e);
        return "Login";
    }
    /**
     * 根据id删除对象
     */
    @RequestMapping(value = "/userdel.do/{id}")
    public String deleteUser(@PathVariable int id){
        System.out.print(id);
        if (userService.deleteUserById(id)<0){
            return "redirect:/sys/user/userList.html";
        }else{
            return "redirect:/sys/user/userList.html";
        }
    }

    @RequestMapping(value = "/userModify.do/{id}")
    public String updateUser(@PathVariable int id,HttpServletRequest request){

        User user=userService.showUser(id);
        request.setAttribute("users",user);
            return "usermodify";
    }
    @RequestMapping(value = "/userUpdate.do/")
    public String userUpdate(@PathVariable User user){

        if (userService.updateUser(user)<0){
            return "redirect:/sys/user/userList.html";
        }else{
            return "redirect:/sys/user/userList.html";
        }

    }
    @RequestMapping(value = "/checkUserCode.do",produces = {"application/json;charset=UTF-8"})
    public String checkUserCode(String userCode){
        Dto dto=new Dto();
        if (userService.checkUserCode(userCode)){
            dto.setCode("1000");//表示userCode存在
            dto.setMessage("userCode.exist");
        }else {
            dto.setCode("200");
            dto.setMessage("userCode.exist");
        }
        String json= JSON.toJSONString(dto);
        return  json;
    }
}

